package com.czy.owner.ui.userinfo;

import android.content.Context;
import android.content.ContextWrapper;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.GridImageAdapter;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.ActionSheetDialog;
import com.czy.owner.widget.FullyGridLayoutManager;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.FunctionOptions;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.czy.owner.R.id.recycler;


/**
 * Created by wangyang on 2017/5/10 0010.
 * 意见反馈
 */

public class FeedBackActivity extends BaseActivity {
    @BindView(R.id.tv_str_length)
    TextView tvStrLength;
    @BindView(R.id.et_feedback_content)
    EditText etFeedbackContent;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.btn_sure_commit)
    Button btnSureCommit;
    private GridImageAdapter adapter;
    private int selectMode = FunctionConfig.MODE_MULTIPLE;
    private int maxSelectNum = 9;// 图片最大可选数量
    private int selectType = FunctionConfig.TYPE_IMAGE;
    private int copyMode = FunctionConfig.CROP_MODEL_DEFAULT;
    private boolean enablePreview = true;
    private boolean isPreviewVideo = true;
    private boolean selectImageType = false;
    private int cropW = 0;
    private int cropH = 0;
    private int maxB = 0;
    private int compressW = 0;
    private int compressH = 0;
    private boolean isCompress = false;
    private boolean isCheckNumMode = true;
    private int compressFlag = 1;// 1 系统自带压缩 2 luban压缩
    private List<LocalMedia> selectMedia = new ArrayList<>();
    private int themeStyle;
    private int previewColor, completeColor, previewBottomBgColor, previewTopBgColor, bottomBgColor, checkedBoxDrawable;
    private boolean clickVideo = false;


    private MyLoadView myLoadView;
    private String feedBackUrl = "";
    private String feedback = "system";
    private boolean isFlagCamera = true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.feedback_suggestion);

        etFeedbackContent.addTextChangedListener(new FeedBackActivity.NewWatcher());
        feedback = getIntent().getStringExtra("feedback");
        if (feedback.equals("system")) {
            getToolbarTitle().setText(getResources().getString(R.string.feedback_system));
            feedBackUrl = Constants.OWN_FEEDBACK;
        } else if (feedback.equals("store")) {
            feedBackUrl = Constants.OWN_FEEDBACKSTORE;
            getToolbarTitle().setText(getResources().getString(R.string.feedback_store));
        }
        myLoadView = new MyLoadView(FeedBackActivity.this, "正在上传");


        FullyGridLayoutManager manager = new FullyGridLayoutManager(FeedBackActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(FeedBackActivity.this, onAddPicClickListener);
        adapter.setList(selectMedia);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);


        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                switch (selectType) {
                    case FunctionConfig.TYPE_IMAGE:
                        // 预览图片 可长按保存 也可自定义保存路径
                        //PictureConfig.getInstance().externalPicturePreview(MainActivity.this, "/custom_file", position, selectMedia);
                        PictureConfig.getInstance().externalPicturePreview(FeedBackActivity.this, position, selectMedia);
                        break;
                    case FunctionConfig.TYPE_VIDEO:
                        // 预览视频
                        if (selectMedia.size() > 0) {
                            PictureConfig.getInstance().externalPictureVideo(FeedBackActivity.this, selectMedia.get(position).getPath());
                        }
                        break;
                }

            }
        });

    }

    @Override
    protected void updateViews() {

    }


    /**
     * 删除图片回调接口
     */

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick(final int type, int position) {
            switch (type) {
                case 0:
                    new ActionSheetDialog(FeedBackActivity.this).builder()
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            isFlagCamera = true;
                                            cameraPhoto(true);

                                        }
                                    })
                            .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            isFlagCamera = false;
                                            cameraPhoto(false);
                                        }
                                    }).show();
                    break;


                case 1:
                    // 删除图片
                    selectMedia.remove(position);
                    adapter.notifyItemRemoved(position);
                    break;
            }
        }
    };


    private void cameraPhoto(boolean model) {
        // 进入相册
        /**
         * type --> 1图片 or 2视频
         * copyMode -->裁剪比例，默认、1:1、3:4、3:2、16:9
         * maxSelectNum --> 可选择图片的数量
         * selectMode         --> 单选 or 多选
         * isShow       --> 是否显示拍照选项 这里自动根据type 启动拍照或录视频
         * isPreview    --> 是否打开预览选项
         * isCrop       --> 是否打开剪切选项
         * isPreviewVideo -->是否预览视频(播放) mode or 多选有效
         * ThemeStyle -->主题颜色
         * CheckedBoxDrawable -->图片勾选样式
         * cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
         * cropH-->裁剪高度 值不能小于100
         * isCompress -->是否压缩图片
         * setEnablePixelCompress 是否启用像素压缩
         * setEnableQualityCompress 是否启用质量压缩
         * setRecordVideoSecond 录视频的秒数，默认不限制
         * setRecordVideoDefinition 视频清晰度  Constants.HIGH 清晰  Constants.ORDINARY 低质量
         * setImageSpanCount -->每行显示个数
         * setCheckNumMode 是否显示QQ选择风格(带数字效果)
         * setPreviewColor 预览文字颜色
         * setCompleteColor 完成文字颜色
         * setPreviewBottomBgColor 预览界面底部背景色
         * setBottomBgColor 选择图片页面底部背景色
         * setCompressQuality 设置裁剪质量，默认无损裁剪
         * setSelectMedia 已选择的图片
         * setCompressFlag 1为系统自带压缩  2为第三方luban压缩
         * 注意-->type为2时 设置isPreview or isCrop 无效
         * 注意：Options可以为空，默认标准模式
         */

        themeStyle = ContextCompat.getColor(FeedBackActivity.this, R.color.appThemeColor);
        if (selectImageType) {
            checkedBoxDrawable = R.drawable.select_cb;
        } else {
            checkedBoxDrawable = 0;
        }

        if (isCheckNumMode) {
            // QQ 风格模式下 这里自己搭配颜色
            previewColor = ContextCompat.getColor(FeedBackActivity.this, R.color.blue);
            completeColor = ContextCompat.getColor(FeedBackActivity.this, R.color.blue);
        }

        FunctionOptions options = new FunctionOptions.Builder()
                .setType(selectType) // 图片or视频 FunctionConfig.TYPE_IMAGE  TYPE_VIDEO
                .setCropMode(copyMode) // 裁剪模式 默认、1:1、3:4、3:2、16:9
                .setCompress(isCompress) //是否压缩
                .setEnablePixelCompress(true) //是否启用像素压缩
                .setEnableQualityCompress(true) //是否启质量压缩
                .setMaxSelectNum(maxSelectNum) // 可选择图片的数量
                .setMinSelectNum(0)// 图片或视频最低选择数量，默认代表无限制
                .setSelectMode(selectMode) // 单选 or 多选
                .setShowCamera(false) //是否显示拍照选项 这里自动根据type 启动拍照或录视频
                .setEnablePreview(enablePreview) // 是否打开预览选项
                .setEnableCrop(false) // 是否打开剪切选项
                .setCircularCut(false)// 是否采用圆形裁剪
                .setPreviewVideo(isPreviewVideo) // 是否预览视频(播放) mode or 多选有效
                .setCheckedBoxDrawable(checkedBoxDrawable)
                .setRecordVideoDefinition(FunctionConfig.HIGH) // 视频清晰度
                .setRecordVideoSecond(60) // 视频秒数
                .setCustomQQ_theme(0)// 可自定义QQ数字风格，不传就默认是蓝色风格
                .setGif(false)// 是否显示gif图片，默认不显示
                .setCropW(cropW) // cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
                .setCropH(cropH) // cropH-->裁剪高度 值不能小于100 如果值大于图片原始宽高 将返回原图大小
                .setMaxB(maxB) // 压缩最大值 例如:200kb  就设置202400，202400 / 1024 = 200kb
                .setPreviewColor(previewColor) //预览字体颜色
                .setCompleteColor(completeColor) //已完成字体颜色
                .setPreviewBottomBgColor(previewBottomBgColor) //预览图片底部背景色
                .setPreviewTopBgColor(previewTopBgColor)//预览图片标题背景色
                .setBottomBgColor(bottomBgColor) //图片列表底部背景色
                .setGrade(Luban.THIRD_GEAR) // 压缩档次 默认三档
                .setCheckNumMode(isCheckNumMode)
                .setCompressQuality(100) // 图片裁剪质量,默认无损
                .setImageSpanCount(4) // 每行个数
                .setVideoS(0)// 查询多少秒内的视频 单位:秒
                .setSelectMedia(selectMedia) // 已选图片，传入在次进去可选中，不能传入网络图片
                .setCompressFlag(compressFlag) // 1 系统自带压缩 2 luban压缩
                .setCompressW(compressW) // 压缩宽 如果值大于图片原始宽高无效
                .setCompressH(compressH) // 压缩高 如果值大于图片原始宽高无效
                .setThemeStyle(themeStyle) // 设置主题样式
                .setNumComplete(false) // 0/9 完成  样式
                .setClickVideo(clickVideo)// 点击声音
//                            .setPicture_title_color(ContextCompat.getColor(FeedBackActivity.this, R.color.black)) // 设置标题字体颜色
//                            .setPicture_right_color(ContextCompat.getColor(FeedBackActivity.this, R.color.black)) // 设置标题右边字体颜色
//                            .setLeftBackDrawable(R.mipmap.back2) // 设置返回键图标
//                            .setStatusBar(ContextCompat.getColor(FeedBackActivity.this, R.color.white)) // 设置状态栏颜色，默认是和标题栏一致
//                            .setImmersive(false)// 是否改变状态栏字体颜色(黑色)
                .create();

        if (model) {
            // 先初始化参数配置 拍照
            PictureConfig.getInstance().init(options).startOpenCamera(FeedBackActivity.this, resultCallback);
        } else {
            // 先初始化参数配置，启动相册
            PictureConfig.getInstance().init(options).openPhoto(FeedBackActivity.this, resultCallback);
        }

    }


    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            // 多选回调
            if (isFlagCamera) {
                selectMedia.addAll(resultList);
            } else {
                selectMedia = resultList;
            }

            MyLog.e("callBack_result", selectMedia.size() + "");
            LocalMedia media = resultList.get(0);
            if (media.isCut() && !media.isCompressed()) {
                // 裁剪过
                String path = media.getCutPath();
            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                String path = media.getCompressPath();
            } else {
                // 原图地址
                String path = media.getPath();
            }
            if (selectMedia != null) {
                adapter.setList(selectMedia);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onSelectSuccess(LocalMedia media) {
            // 单选回调
            selectMedia.add(media);
            if (selectMedia != null) {
                adapter.setList(selectMedia);
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }


    //    验证输入框
    public class NewWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            tvStrLength.setText("剩余" + (200 - etFeedbackContent.getText().toString().length()) + "个字符");
        }

    }

    @OnClick(R.id.btn_sure_commit)
    public void btnSureCommitOnClick(View view) {
        if (etFeedbackContent.getText().toString().equals("")) {
            PhoneUtils.ShowToastMessage(FeedBackActivity.this, "写出你的问题...");
            etFeedbackContent.requestFocus();
            return;
        }

        if (etFeedbackContent.getText().toString().length() < 6) {
            PhoneUtils.ShowToastMessage(FeedBackActivity.this, "你的问题描述太短...");
            etFeedbackContent.requestFocus();
            return;
        }

        if (etFeedbackContent.getText().toString().trim().isEmpty()) {
            PhoneUtils.ShowToastMessage(FeedBackActivity.this, "反馈意见不能全部为空格");
            etFeedbackContent.requestFocus();
            return;
        }

        UpLoadText(etFeedbackContent.getText().toString().trim());

    }

    //    上传文本反馈内容
    private void UpLoadText(String owntext) {
        myLoadView.ShowLoadView();
        btnSureCommit.setEnabled(false);
        String url = Constants.APP_API_BASE + feedBackUrl;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(FeedBackActivity.this).getSession());
        params.addBodyParameter("content", owntext);
        if (feedBackUrl.equals("/own/feedbackStore")) {
            params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(FeedBackActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        }
        params.setMultipart(true);
        try {
            if (selectMedia.size() > 0) {
                for (int i = 0; i < selectMedia.size(); i++) {
                    params.addBodyParameter("file" + (i + 1), new FileInputStream(new File(selectMedia.get(i).getPath())), "img/jpg", "pic" + i + ".jpg");
                    MyLog.e("yang", "图片地址==" + selectMedia.get(i).getPath() + "\n图片个数==" + selectMedia.size());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    myLoadView.CancleLoadView();
                    PhoneUtils.ShowToastMessage(FeedBackActivity.this, "上传成功");
                    btnSureCommit.setEnabled(true);
                    finish();

                } else {
                    myLoadView.CancleLoadView();
                    PhoneUtils.ShowToastMessage(FeedBackActivity.this, exp);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                myLoadView.CancleLoadView();
            }
        });

    }
}
